package com.example.common.controller;

import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.example.common.utils.jwt.JwtUtils;
import com.example.common.resp.Response;
import com.example.sys.entity.UserInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ZhengDing
 * @date 2022/2/20 15:10
 */
@Slf4j
@RestController
@RequestMapping("sys/jwt")
@Api(tags = "JWT")
public class JwtController {
    
    @Autowired
    private JWTVerifier jwtVerifier;
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class TokenInfo {
        private String token;
    }
    
    @ApiOperation("TEST-创建token")
    @RequestMapping("test/create")
    public Response testCreate() {
        try {
            String jwtToken = JwtUtils.createJWTTokenExpireOneMinute(new UserInfo(1, "admin", "123456", "管理员", "admin@hs.com"));
            TokenInfo tokenInfo = new TokenInfo(jwtToken);
            return Response.buildSuccess(tokenInfo);
        } catch (JWTCreationException e) {
            e.printStackTrace();
            return Response.buildError("token 创建失败");
        }
        //return Response.buildSuccess();
    }
    
    @RequestMapping("test/verify")
    @ApiOperation("TEST-检验token")
    public Response testVerify(@RequestParam(value = "token", required = false) String token0, HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("token: " + token);
        if (StringUtils.isEmpty(token)) {
            return Response.buildError("未获取到token", 403);
        }
        try {
            //JWTUtils.verifyJWTToken(headerToken);
            
            // 使用 JWTVerifier 单例 bean 来进行验证
            jwtVerifier.verify(token);
            log.error("token 校验成功: " + token);
        } catch (TokenExpiredException e) {
            log.error("token 已过期: " + token);
            return Response.buildError("token 已过期");
        } catch (JWTVerificationException e) {
            log.error("token 校验失败: " + token);
            return Response.buildError("token 校验失败");
        } catch (Exception e) {
            log.error("token 校验失败: " + token);
            return Response.buildError("token 校验失败");
        }
        return Response.buildSuccess();
    }
}
